﻿using Basic.WxModel.DB;
using Basic.WxModel.WxMsgFilter;
using Basic.WxRemoteModel.WxMsg.Model;
using Basic.WxRepository;
using WeDonekRpc.Client.Attr;
using WeDonekRpc.Client.Interface;
using WeDonekRpc.Client.Ioc;
using WeDonekRpc.Helper;
using WeDonekRpc.Helper.IdGenerator;
using WeDonekRpc.Helper.Interface;

namespace Basic.WxCollect.lmpl
{
    [ClassLifetimeAttr(ClassLifetimeType.SingleInstance)]
    internal class WxForwardLogCollect : IWxForwardLogCollect
    {
        private readonly IIocService _Ioc;

        private readonly IDelayDataSave<DBWxForwardLog> _DelaySave;

        public WxForwardLogCollect ( IIocService ioc )
        {
            this._Ioc = ioc;
            this._DelaySave = new DelayDataSave<DBWxForwardLog>(this._Save, 10000, 10);
        }

        private void _Save ( ref DBWxForwardLog[] datas )
        {
            using ( IocScope scope = this._Ioc.CreateScore() )
            {
                IWxForwardLogRepository repository = scope.Resolve<IWxForwardLogRepository>();
                repository.Adds(datas);
            }
        }
        public void Add ( WxMsgBody msg, WxMsgFilterDto filter, ErrorException ex )
        {
            this._DelaySave.AddData(new DBWxForwardLog
            {
                AppId = msg.PlatformAppId,
                WxAppId = msg.WxAppId,
                IsEvent = false,
                ErrorCode = ex.ErrorCode,
                IsSuccess = false,
                SystemType = filter.SystemType,
                MsgId = msg.MsgId,
                AddTime = msg.CreateTime.ToDateTime(),
                MsgType = msg.MsgType,
                Direct = filter.Direct,
                ForwardType = filter.ForwardType,
                Reply = filter.Reply,
                RpcMerId = filter.RpcMerId,
                Id = IdentityHelper.CreateId()
            });
        }
        public void Add ( WxMsgEventBody msg, WxMsgFilterDto filter, ErrorException ex )
        {
            this._DelaySave.AddData(new DBWxForwardLog
            {
                AppId = msg.PlatformAppId,
                WxAppId = msg.WxAppId,
                IsEvent = true,
                ErrorCode = ex.ErrorCode,
                IsSuccess = false,
                SystemType = filter.SystemType,
                MsgId = msg.MsgId,
                AddTime = msg.CreateTime.ToDateTime(),
                MsgType = msg.EventType,
                Direct = filter.Direct,
                ForwardType = filter.ForwardType,
                Reply = filter.Reply,
                RpcMerId = filter.RpcMerId,
                Id = IdentityHelper.CreateId()
            });
        }
    }
}
